<?php

namespace Controller\Ajax;

class File extends Base {

	public function coords() {
		if ($this->isPost() && $this->postParam('file')) {
			$file = $this->cutImage(600, 600);
			$this->cutImage(400, 400);
			$this->cutImage(200, 200);
			// 保存用户头像路径到数据库
			\Business\User::instance()->updateUserPhoto($this->currentUserInfo['UserId'], $file);
			@unlink($file);
			$successFile = \Util\User::getUserPhoto($file, 200, 200);
			$result = array(
				$successFile,
				$file,
			);
			$this->response($result);
		}
	}

	public function uploadDogPhoto() {
		if ($this->isPost() && $this->postParam('file')) {
			$file = $this->cutImage(600, 600);
			$this->cutImage(400, 400);
			$this->cutImage(200, 200);
			// 保存用户头像路径到数据库
			@unlink($file);
			$successFile = \Util\User::getUserPhoto($file, 200, 200);
			$result = array(
				$successFile,
				$file,
			);
			$this->response($result);
		}
	}

	public function editorUpload() {
		$config = array(
			'savePath' => 'upload/',             //存储文件夹
			'maxSize' => 102400 ,                   //允许的文件最大尺寸，单位KB
			'allowFiles' => array('.gif' , '.png' , '.jpg' , '.jpeg')  //允许的文件格式
		);
		//上传文件目录
		$fileName = '';
		$error = '';
		$info = false;
		if ($_FILES) {
			$up = new \Util\Uploader('imgFile', $config);
			$info = $up->getFileInfo();
			if ($info['state'] == 'SUCCESS') {
				$fileName = $info['url'];
			} else {
				$error = $info['state'];
				echo json_encode(array(
					'error' => 1,
					'message' => $error,
				));exit;
			}
			if ($fileName) {
				$up->cutImage($fileName, 200);
				$up->cutImage($fileName, 400);
				$up->cutImage($fileName, 800);
				$up->cutImage($fileName, 1200);
			}

			$info = array(
				'error' => 0,
				'url' => $fileName ? \Util\User::getUserPhotoRectangle($fileName, 800) : '',
			);
			echo json_encode($info);
		}
	}

	private function cutImage($width, $height) {
		$x = $this->postInt('x');
		$y = $this->postInt('y');
		$w = $this->postInt('w');
		$h = $this->postInt('h');
		$file = $this->postParam('file');
		$size = getimagesize($file);
		$thisWidth = $this->postInt('width');
		$x = $size[0] / $thisWidth * $x;
		$y = $size[0] / $thisWidth * $y;
		$w = $size[0] / $thisWidth * $w;
		$h = $size[0] / $thisWidth * $h;
		$img = imagecreatefromjpeg($file);
		$dst = imagecreatetruecolor($width, $height);
		imagecopyresampled($dst, $img , 0, 0, $x, $y, $width, $height, $w, $h);
		$pathInfo = pathinfo($file);
		$nowFile = $pathInfo['dirname'] . '/' . $pathInfo['filename'] . '_' . $width . '_' . $height . '.' . $pathInfo['extension'];

		switch (strtolower($pathInfo['extension'])) {
			case 'png':
				$fn = 'imagepng';
				break;
			case 'gif':
				$fn = 'imagegif';
				break;
			case 'jpg':
			case 'jpeg':
				$fn = 'imagejpeg';
				break;
			default:
				$this->throwException('图片格式错误');
		}
		$fn($dst, $nowFile,200);
		return $file;
	}

}